import { history } from 'umi'
import moment from 'moment';

export const pushRoute = ({ pathname, query }) => {
    try {
        history.push({
            pathname,
            query
        });
    } catch (error) {
        const arr = [];
        if (query) {
            // eslint-disable-next-line no-restricted-syntax
            for (const [key, value] of Object.entries(query)) {
                arr.push(`${key}=${value}`);
            }
        }
        window.location.href = `${window.location.origin}${pathname}${arr.length > 0 ? '?' : ''}${arr.join('&')}`;
    }
};

export const formatRangeTime = (startTime, endTime) => {
    if (!startTime && !endTime) {
        return '';
    }
    moment.updateLocale('zh-cn', {
        meridiem(hour) {
            if (hour < 12) {
                return '上午';
            }
            if (hour === 12) {
                return '中午';
            }
            return '下午';
        }
    });
    const st = startTime ? moment(startTime) : '';
    const et = endTime ? moment(endTime) : '';
    const date = (st || et).format('YYYY-MM-DD dddd ');
    const stA = st ? st.format('a') : '';
    const etA = et ? et.format('a') : '';
    const stTime = st ? st.format('HH:mm') : '';
    const etTime = et ? et.format('HH:mm') : '';
    return `${date}${stA}${stTime}${st ? '-' : ''}${etA === stA ? '' : etA}${etTime}`;
};
